<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .a {
            width: 40px;
            height: 40px;
            background-color: #f00;
            position: absolute;
        }
    </style>
</head>

<body>

    <div class="a"></div>

    <script>

        var oDiv = document.querySelector('.a');

        document.onkeydown = function (e) {
            var y = oDiv.offsetTop;
            var x = oDiv.offsetLeft;
            console.log(e.keyCode);
            if (e.keyCode === 40) {
                y++;
                oDiv.style.top = y + 'px';
            }
            if (e.keyCode === 38) {
                y--;
                oDiv.style.top = y + 'px';
            }
            if (e.keyCode === 39) {
                x++;
                oDiv.style.left = x + 'px';
            }
            if (e.keyCode === 37) {
                x--;
                oDiv.style.left = x + 'px';
            }
        }

    </script>

</body>

</html>